﻿//潜在客源js
var PreCustomer = {
    preCustomerSwf: null,//swf上传控件实例
    tempTargetEstate: null, //临时的选中目标楼盘，点击确定的时候在页面显示
    tempAssignUser: null //临时的分配人信息
};

PreCustomer.init = function () {
    this.initSwfUpload();
    PreCustomer.cominit();
};
PreCustomer.trustorinit = function () {
    this.estateAutoCompleteByName();
    PreCustomer.cominit();
};
PreCustomer.cominit = function () {
    this.estateAutoComplete();
    this.addTargetEstate();
    this.assignUserAutoComplete();
    this.addAssignUser();
    this.addAssignDeptAutoComplete();
    this.addAssignDept();
    this.ChangeCustormerOwner();
    EmployeePrompt.getDepartAndEmployeeByInput(null, 'hidCustomerOwnerDeptKeyId', 'txtCustomerOwne', 'hidCustomerOwnerUserId', false, 'private', 1, '管理人姓名', null, false, true);
    $.inputStatistics("preCusRemark", 200);
    //x样式的删除
    $(".fclose").live("click", function () {
        $(this).parent().parent().remove();
    });
};

//上传房源清洗数据的excel表格成功后，调用后端服务
PreCustomer.uploadCleanDataSuccess = function (file, serverData) {
    try {
        $("#spanFlashStauts").show();
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("Complete.");
        progress.toggleCancel(false);
        console.log(file);
        $("#hidFilePath").val(serverData);
        $("#spFileName").text(file.name);
        $("#hidFileName").val(file.name);
    } catch (ex) {
        this.debug(ex);
    }
};

PreCustomer.initSwfUpload = function() {
    this.preCustomerSwf = new SWFUpload({
        flash_url: "/Scripts/PageHelper/swfupload1.swf",
        upload_url: $("#uploadPath").val(),
        post_params: { categoryName: "preCustomer" },
        file_size_limit: "2 MB",
        file_types: "*.xlsx;*.xls",
        file_types_description: "2003 excel",
        file_upload_limit: 20,
        file_queue_limit: 20,
        custom_settings: {
            progressTarget: "fsUploadProgress"
        },
        debug: false,
        button_disabled: false,
        button_width: "75",
        button_height: "20",
        button_placeholder_id: "btnUploadCleanData",
        button_cursor: SWFUpload.CURSOR.HAND,
        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
        button_text: '<span class="cleanData">导入潜在客源</span>',
        button_text_style: ".cleanData{color:#1f73f0;}",

        // The event handler functions are defined in handlers.js
        file_queued_handler: fileQueued,
        file_queue_error_handler: fileQueueErrorPreCustomer,
        file_dialog_complete_handler: fileDialogComplete,
        upload_error_handler: uploadError,
        upload_success_handler: this.uploadCleanDataSuccess,
        upload_complete_handler: uploadComplete,
        queue_complete_handler: queueComplete // Queue plugin event
    });
    //上传组件模拟文字链接
    //$("#spanSwfupload").hover(function () {
    //    $(this).find($("#btnUploadCleanData")).css("opacity", "1");
    //    $(this).find($(".abs")).hide();
    //}, function () {
    //    $(this).find($("#btnUploadCleanData")).css("opacity", "0");
    //    $(this).find($(".abs")).show();
    //});
};

function fileQueueErrorPreCustomer(file, errorCode, message) {
    try {
        if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            $.OKDialogAgency('<div class="tc">上传文件太多了。\n' + (message === 0 ? '已经达到上传上限' : '可以上传' + message + '个文件！</div>'));
            return;
        }

        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setError();
        progress.toggleCancel(false);

        switch (errorCode) {
            case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                progress.setStatus("上传文件必须小于2M");
                $.OKDialogAgency('<div class="tc">上传文件必须小于2M！</div>');
                this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                progress.setStatus("Cannot upload Zero Byte files.");
                this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                progress.setStatus("Invalid File Type.");
                this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
            default:
                if (file !== null) {
                    progress.setStatus("Unhandled Error");
                }
                this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
                break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}

//目标楼盘自动完成
PreCustomer.getEstateUrl = function () {
    var estateSearchValue = $("#txtEstateSearchValue").val();
    return '/Estate/auto-match-eatate-search-value?EstateSearchType=1&EstateSearchValue=' + escape(estateSearchValue);
};

PreCustomer.estateAutoComplete = function() {
    //楼盘自动完成及赋值隐藏域
    $("#txtEstateSearchValue").autocomplete(this.getEstateUrl, {
        width: 260,
        max: 1000,
        Default: 1,
        selectFirst: false,
        cacheLength: 0,
        formatItem: function(row) {
            if (row.ItemFullText != null && row.ItemFullText != "") {
                return row.ItemFullText;
            } else {
                return row.ItemText;
            }
        },
        formatResult: function(row) {
            return row.ItemText;
        }
    }).result(function(a, b) {
        PreCustomer.tempTargetEstate = b;
    });
};

PreCustomer.addTargetEstate = function() {
    $("#addToTargetEstate").click(function() {
        var that = PreCustomer.tempTargetEstate;
        if (that == null) {
            $.OKDialogAgency('<div class="tc">请从智能提示中选择目标楼盘！</div>');
            return;
        }

        //判断楼盘是否重复
        if ($("#spanAddEstates").find("span input[name='EstateKeyId'][value='" + that.ItemValue + "']").length > 0) {
            $.OKDialogAgency('<div class="tc">不能重复添加楼盘！</div>');
            return;
        }

        //判断选中的目标楼盘最多为5个
        if ($("#spanAddEstates").find("input[name='EstateName']").length > 4) {
            $.OKDialogAgency('<div class="tc">目标楼盘最多为5个！</div>');
            return;
        }
        var tempStr = '<span name="{0}" class="l">{1}'
            + '<a><input type="hidden" name="EstateKeyId" value="{2}" />'
            + '<input type="hidden" name="EstateName" value="{1}" />'
            + '<i class="fclose">×</i></a>'
            + '</span>';

        PreCustomer.tempTargetEstate = null;
        $("#txtEstateSearchValue").val("");
        //拼接显示的目标楼盘
        $("#spanAddEstates").append(tempStr.format(that.ItemText, that.ItemText, that.ItemValue));
    });
};

//目标楼盘自动完成
PreCustomer.EstateUrl = function () {
    var estateName = $('#txtEstateNames').val().split('+');
    return "/estate/AutoEstate?EstateName=" + escape(estateName[estateName.length - 1]);
};
PreCustomer.estateAutoCompleteByName = function() {
    $("#txtEstateNames").autocomplete(PreCustomer.EstateUrl, {
        width: 260,
        max: 1000,
        Default: 1,
        selectFirst: false,
        cacheLength: 0,
        multiple: true,
        multipleSeparator: '+',
        formatItem: function(row) {
            return row.EstateFullName;
        },
        formatResult: function(row) {
            return row.EstateName;
        }
    }).result(function(a, b) {
        $("#txtEstateNames").attr('isexistbuild', 'true');
    });
}

//员工分配自动完成
PreCustomer.getAssignUserUrl = function () {
    var estateSearchValue = $("#txtAssignUser").val();
    return "/property/user-auto-complete-obtain-ajax?name=" + escape(estateSearchValue) + '&ExceptMe=false&hasPublicAccount=false';
};

//分配人
PreCustomer.assignUserAutoComplete = function () {
    $("#txtAssignUser").autocomplete(this.getAssignUserUrl, {
        width: 260,
        max: 1000,
        Default: 1,
        selectFirst: false,
        cacheLength: 0,
        formatItem: function (row) {
            if (row.IsPublicAccount) {
                return row.UserName + "<span style='float:right'>" + row.DepartmentName + "</span>";
            } else {
                return row.UserName + "(" + row.EmployeeNo + ")<span style='float:right'>" + row.DepartmentName + "</span>";
            }
        },
        formatResult: function (row) {
            return row.UserName;
        }
    }).result(function (a, b) {
        PreCustomer.tempAssignUser = b;
    });
}

PreCustomer.addAssignUser = function () {
    $("#addAssignUser").click(function () {
        var that = PreCustomer.tempAssignUser;
        if (that == null) {
            $.OKDialogAgency('<div class="tc">请从智能提示中选择分配人！</div>');
            return;
        }
        //判断分配人是否重复
        if ($("#spanAddContacts").find("span input[name='AssignUserKeyId'][value='" + that.UserKeyId + "']").length > 0) {
            $.OKDialogAgency('<div class="tc">不能重复添加分配人！</div>');
            return;
        }

        var tempStr = '<span name="{0}" class="l">{1}'
            + '<a><input type="hidden" name="AssignUserKeyId" value="{2}" />'
            + '<input type="hidden" name="AssignUserDeptKeyId" value="{3}" />'
            + '<i class="fclose">×</i></a>'
            + '</span>';

        PreCustomer.tempAssignUser = null;
        $("#txtAssignUser").val("");
        //拼接分配人
        $("#spanAddContacts").append(tempStr.format(that.UserName, that.UserName, that.UserKeyId, that.DepartmentKeyId));
    });
}

//分配部门
PreCustomer.addAssignDeptAutoComplete = function () {
    $("#txtAssignDept").click(function () {
        var deptKeyId = $("#hidCustomerOwnerDeptKeyId").val();
        if (!deptKeyId) {
            $.OKDialogAgency('<div class="tc">请选择管理人！</div>');
            return;
        }
        $("#tt").tree({
            url: '/Org/find-lowinheritandself-departments?depaertmentKeyId=' + deptKeyId + '',
            checkbox: false,
            method: 'get',
            animate: true,
            lines: true,
            state: "closed",
            onLoadSuccess: function () {
                $("#tt").tree("collapseAll");
                $(".easyui-panel").css("width", "320px");
            }
        });
    })
};

PreCustomer.addAssignDept = function () {
    $("#addAssignDept").click(function () {
        //获取选中项
        //var nodes = $('#tt').tree('getChecked');

        var nodes = $('#tt').tree('getSelected');
        if (nodes == null || nodes.length == 0) {
            $.OKDialogAgency('<div class="tc">请在列表树种选择要分配的部门！</div>');
            return;
        }

        //判断楼盘是否重复
        if ($("#spanAddDept").find("span input[name='AssignDepartmentKeyId'][value='" + nodes.id + "']").length > 0) {
            $.OKDialogAgency('<div class="tc">不能重复添加分配部门！</div>');
            return false;
        }

        var tempStr = '<span name="{0}" class="l">{1}'
            + '<a><input type="hidden" name="AssignDepartmentKeyId" value="{2}" />'
            + '<i class="fclose">×</i></a>'
            + '</span>';

        $("#txtAssignDept").val("");

        var spanHtml = "";
        spanHtml = tempStr.format(nodes.text, nodes.text, nodes.id)
        $("#spanAddDept").append(spanHtml);

        ////拼接显示的目标楼盘

        //var parentId = "0";
        //for (var i = 0; i < nodes.length; i++) {
        //    var nodeParent = $("#tt").tree("getParent", nodes[i].target);//
        //    if (nodeParent && nodeParent.checked) {
        //        continue;
        //    }

        //    if (parentId == nodes[i].parentId) {
        //        continue;
        //    }

        //    var nodeChildren = $("#tt").tree("getChildren", nodes[i].target);//查看子节点
        //    if (nodeChildren.length && nodes[i].checked) {
        //        parentId = nodes[i].id;
        //    }

        //    //判断楼盘是否重复
        //    if ($("#spanAddDept").find("span[name='" + nodes[i].text + "']").length > 0) {
        //        $.OKDialogAgency('<div class="tc">不能重复添加分配部门！</div>');
        //        return;
        //    }

        //    spanHtml = tempStr.format(nodes[i].text, nodes[i].text, nodes[i].id)
        //    $("#spanAddDept").append(spanHtml);
        //}
    });
}

PreCustomer.ChangeCustormerOwner = function () {
    $("#txtCustomerOwne").change(function () {
        $("#tt").html('');
        $("#spanAddDept").html('');
    });
}

function OnSucessFun(data) {
    if (data.OperateResult) {
        $.dialog({
            content: '<div class="tc">导入成功！</div>',
            lock: true,
            ok: function () {
                $("#btnSubmit").submit()
            },
            cancel: false
        });
    }
    else {
        $.OKDialogAgency(data.FaildReason);
    }
}